<template lang="pug">
  .CustomerSalaryImportModal
    Modal(
      v-model="isShowCustomerSalaryImportModal"
      title="批量导入"
      class-name="vertical-center-modal"
      width="600"
    )
      Form(ref="formImport" :model="formImport" :rules="rules" :label-width="160")
        FormItem.form-item(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-show="item.isShow")
          template(v-if="item.type === 'text'")
            .line-h-30 {{formImport[item.model]}}
          template(v-if="item.type === 'input'")
            Input(v-model="formImport[item.model]" :placeholder="item.placeholder" @on-blur="getCompanyList")
          template(v-if="item.type === 'select'")
            Select(v-model="formImport[item.model]" :placeholder="item.placeholder" @on-change="handlePublicChange(item.model, $event)")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.label}}
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(v-model="formImport[item.model]" placeholder="请选择" type="year" @on-change="handlePublicChange(item.model, $event)")
          template(v-if="item.model === 'fileName'")
            Row
              Col.pl-10(span="24")
                //- a.pull-left.mr-10.my-btn.btn-default(type="primary" :href="templateDownLoadUrl") 模板下载
                Button.pull-left.mr-10(:to="templateDownLoadUrl" target="_blank") 模板下载
                Upload(
                  ref="upload"
                  :max-size="10 * 1024"
                  :on-exceeded-size="handleMaxSizeTen"
                  :action="baseUrl + 'api/YearReviewBaseAmount/Upload'"
                  :before-upload="handleBeforeUpload"
                  :on-success="handleUploadSuccess"
                  :on-remove="handleUploadRemove"
                  accept=".xls, .xlsx"
                  :headers="headers"
                )
                  Button(type="info" :loading="importExcel.uploadLoading" @click="handleUploadFile" :disabled="!isCanUpload") 导入
              Col.pl-10(span="24")
                .text-gray-9.pb-10 仅支持上传10M以内的xlsx文件
            Row(v-if="errorData.isError && !isCanUpload")
              Col.pl-10(span="24")
                //- Button(type="info") 导出错误数据附件
                //- a(type="primary" :href="errorData.downLoadUrl") 导出错误数据附件
                Button(type="warning" :to="errorData.downLoadUrl" target="_blank") 错误数据下载
              //- Col.pl-10(span="24")
              //-   input.pull-left.mr-10(type="file" @change="fileChange")
              //-   a(type="primary" :href="downLoadUrl") 模板
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(v-if="isNowMonth" type="primary" @click="handleShowFurtherModal") 确定
        Button(v-if="!isNowMonth" type="primary" @click="handleImport" :loading="!isCanSubmit") 确定

      //- Table(:columns="importExcel.tableTitle" :data="importExcel.tableData" :loading="importExcel.tableLoading")
    Modal(
      v-model="isShowFurtherModal"
      class-name="vertical-center-modal"
      width="480"
      @on-ok="handleImport"
    )
      p.font-16.text-center.pt-20.pb-20 当前月份账单未核对，请认真检查后再导入薪资！
</template>

<script>
import Cookies from 'js-cookie'
import { Common } from '@/utils/common.js'
import { YearReviewBaseAmountApi } from '@/api/YearReviewBaseAmount.api.js'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'CustomerSalaryImportModal',

  watch: {
  },

  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      baseUrl: baseUrl,
      isShowCustomerSalaryImportModal: false,
      isShowFurtherModal: false,
      isNowMonth: false,
      baseUrl: baseUrl,
      formImport: {
        year: '',
        securityType: '',
        securityNO: '',
        customerId: '',
        fileName: ''
      },
      formItem: [
        { type: 'datePicker', label: '年审年度：', placeholder: '请选择年审年度', prop: 'year', model: 'year', style: 'is-required', isShow: true },
        { type: 'select', label: '参保类型：', placeholder: '请选择参保类型', prop: 'securityType', model: 'securityType', style: 'is-required', isShow: true, options: 'SecurityType' },
        { type: 'input', label: '参保编号：', placeholder: '请输入参保编号', prop: 'securityNO', model: 'securityNO', style: 'is-required', isShow: true },
        { type: 'select', label: '所属公司：', placeholder: '请选择所属公司', prop: 'customerId', model: 'customerId', style: 'is-required', isShow: true, options: 'companyList' },
        { type: 'fileName', label: '选择文件：', placeholder: '请输入选择文件', prop: 'fileName', model: 'fileName', style: 'is-required', isShow: true }
      ],
      rules: {
        year: [
          { required: true, message: '请选择年审年度' }
        ],
        securityType: [
          { required: true, message: '请选择参保类型' }
        ],
        securityNO: [
          { required: true, message: '请输入参保编号' }
        ],
        customerId: [
          { required: true, message: '请选择所属公司' }
        ],
        fileName: [
          { required: true, message: '请输入选择文件' }
        ]
      },
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null,
        tableData: [],
        tableTitle: [],
        tableLoading: false
      },
      arrListDown: {
        tempOps: [],
        SecurityType: [],
        companyList: []
      },
      templateDownLoadUrl: baseUrl + 'Content/Template/批量导入年审基数模板.xls?random=' + Math.floor(Math.random()*10),
      // templateDownLoadUrl: null,
      // isError: false
      errorData: {
        errorId: '',
        isError: false,
        downLoadUrl: baseUrl + 'api/CustomerSalary/ExportErrorFile?fileName='
      },
      isCanUpload: true,
      isCanSubmit: true,
      axsEnableSwitch: false
    }
  },

  mounted () {
    this.getEnum()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, param) {
      this[methodsWords](param)
    },

    // 数据字典
    getEnum () {
      let groupName = 'YearAdjustment.SecurityType'
      Common.getEnum3(groupName, this.arrListDown)
      console.log('数据字典：', this.arrListDown)
    },

    cancel () {
      this.isShowCustomerSalaryImportModal = false
    },

    show () {
      this.$refs.formImport.resetFields()
      this.isCanSubmit = true
      this.isShowCustomerSalaryImportModal = true
    },

    handleUploadFile () {
      Common.initUpload(this.importExcel)
    },

    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      console.log('file: ', file)
      console.log('fileExt: ', fileExt)
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        Common.readFile(file, this.importExcel)
        this.importExcel.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
    },

    handleUploadSuccess (res, file, fileList) {
      console.log('＋ 应发工资导入文件res: ', res)
      console.log('＋ 应发工资导入文件file: ', file)
      console.log('＋ 应发工资导入文件fileList: ', fileList)
      if (res.success) {
        this.formImport.fileName = res.data
        // this.importExcel.file = fileList
        this.isCanUpload = false
      }
      console.log('💗', this.formImport)
    },

    handleUploadRemove (res, file, fileList) {
      this.isCanUpload = true
      console.log('✂ 应发工资导入文件res: ', res)
      console.log('✂ 应发工资导入文件file: ', file)
      console.log('✂ 应发工资导入文件fileList: ', fileList)
    },

    // handleInputChange (val) {
    //   // console.log('💧 model: ', model)
    //   console.log('💧 value: ', value)
    //   // this.formImport[model] = val
    // },

    handlePublicChange (model, value) {
      console.log('💧 model: ', model)
      console.log('💧 value: ', value)
      this.formImport[model] = value
      this.getCompanyList()
    },

    async getCompanyList () {
      var params = {
        Year: this.formImport.year,
        SecurityType: this.formImport.securityType,
        SecurityNO: this.formImport.securityNO,
      }
      let res = await YearReviewBaseAmountApi.getCompanyList(params)
      console.log('🍇 res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        result.map(item => {
          item.label = item.text
        })
        this.arrListDown.companyList = result
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 年审基数预发导入
    async handleImport () {
      console.log('年审基数预发导入params: ', this.formImport)
      this.$refs.formImport.validate((valid) => {
        if (valid) {
          YearReviewBaseAmountApi.import(this.formImport).then(res => {
            console.log('年审基数预发导入res: ', res)
            if (res.status === 200 && res.data.success) {
              this.isCanSubmit = false
              this.$Message.success(res.data.message)
              this.errorData.isError = false
              this.isShowCustomerSalaryImportModal = false
              this.$emit('query')
            } else {
              this.isCanSubmit = true
              
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
              this.isShowCustomerSalaryImportModal = true
              if (res.data.data) {
                this.errorData.isError = true
                this.errorData.errorId = res.data.data
                this.errorData.downLoadUrl = baseUrl + 'api/YearReviewBaseAmount/ExportErrorFile?fileName=' + res.data.data
              }
            }
          })
        }
      })
    },

    handleClearFiles () {
      var file = this.$refs.upload
      if (file && file.length) {
        file.forEach(item => {
          item.clearFiles()
        })
      }
    },

    handleShowFurtherModal () {
      this.isShowFurtherModal = true
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
